import React, { useEffect, useState, useRef } from 'react'
import { Button, Table, Switch, Modal } from 'antd'
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm'

const { confirm } = Modal
const UserList = () => {
  const [regions, getRegions] = useState([])
  const [roles, getRoles] = useState([])
  const [users, getUsers] = useState([])
  const [isShoeModel, getIsShowModel] = useState(false)
  const [titleName, getTitleName] = useState('修改')
  const [currentId, getCurrentId] = useState()
  const [isDisable, getIsDisable] = useState()
  const addForm = useRef(null)

  useEffect(() => {
    getRegionsList()
    getRolesList()
    getUsersList()
  }, [])
  const getRegionsList = () => {
    axios.get('/regions').then((res) => {
      getRegions(res.data)
    })
  }
  const getRolesList = () => {
    axios.get('/roles').then((res) => {
      getRoles(res.data)
    })
  }
  const getUsersList = () => {
    axios.get('/users?_expand=role').then((res) => {
      getUsers(res.data)
    })
  }

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region',
      render: (region) => {
        return <b>{region === '' ? '全球' : region}</b>
      },
      filters: [
        ...regions.map((item) => ({
          text: item.title,
          value: item.value,
        })),
        {
          text: '全球',
          value: '全球',
        },
      ],
      onFilter: (value, item) => {
        if (value === '全球') {
          return item.region === ''
        } else {
          return item.region === value
        }
      },
    },
    {
      title: '角色名',
      dataIndex: 'role',
      render: (role) => {
        return role?.roleName
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return (
          <Switch checked={roleState} onChange={() => onChange(item)}></Switch>
        )
      },
    },
    {
      title: '操作',
      key: 'operate',
      render: (item) => {
        return (
          <div>
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => confirmMethod(item)}
            />
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => onEditOut(item)}
            />
          </div>
        )
      },
    },
  ]
  //改变用户状态
  const onChange = (item) => {
    axios
      .patch(`/users/${item.id}`, {
        roleState: !!!item.roleState,
      })
      .then((res) => {
        getUsersList()
      })
  }
  //删除
  const confirmMethod = (item) => {
    confirm({
      title: '你确定删除该项？',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deletMethod(item)
      },
      onCancel() {},
    })
  }
  const deletMethod = (item) => {
    axios.delete(`/users/${item.id}`).then((res) => {
      getUsersList()
    })
  }
  //新增用户
  const addUser = () => {
    getIsShowModel(true)
    getTitleName('新增')
  }
  //修改
  const onEditOut = async (item) => {
    await getIsShowModel(true)
    await addForm.current.setFieldsValue(item)
    getTitleName('修改')
    getIsDisable(item.roleId)
    getCurrentId(item.id)
  }
  //提交
  const handleOk = () => {
    addForm.current.validateFields().then((value) => {
      if (titleName === '新增') {
        axios
          .post(`http://localhost:5000/users`, {
            ...value,
            roleState: true,
            default: false,
          })
          .then((res) => {
            getUsersList()
            getIsShowModel(false)
          })
      } else {
        axios
          .patch(`http://localhost:5000/users/${currentId}`, {
            ...value,
          })
          .then((res) => {
            getUsersList()
            getIsShowModel(false)
          })
      }
    })
  }
  return (
    <div>
      <Button type="primary" onClick={addUser}>
        +新增
      </Button>
      <Table
        columns={columns}
        dataSource={users}
        pagination={{
          pageSize: 5,
        }}
      />
      <Modal
        title={titleName}
        open={isShoeModel}
        onOk={handleOk}
        onCancel={() => getIsShowModel(false)}
        okText="确认"
        cancelText="取消"
      >
        <UserForm regions={regions} roles={roles} ref={addForm} isDisable={isDisable}></UserForm>
      </Modal>
    </div>
  )
}
export default UserList
